<template>
  <div >
    <div class="px-5 mx-2 pt-2 mb-4 border rounded-lg bg-slate-300">    
      <el-text class="mx-1 font-bold">设备连接设置</el-text>
      <div class="mx-2 my-1 flex">
        <el-checkbox label="通道1开启" class="w-1/6" v-model="conf.stream[0].enable" size="large" :disabled="work_state==1"/>
        <div class="w-1/3">
          <el-select size="large" v-model="conf.stream[0].com_1" value-key="id" placeholder="选择连接方式"  style="width: 240px" :disabled="work_state==1">
            <el-option v-for="item in com_options" :key="item.id" :label="item.label" :value="item.label" />
          </el-select>
          <el-button type="primary" size="large" :icon="RefreshRight" @click="refresh_com(0)"  :disabled="work_state==1"/>
        </div>
        <div class="w-1/3">
          <el-select class="ml-2" size="large" v-model="conf.stream[0].com_2" value-key="id" placeholder="选择读头设备"  style="width: 240px" :disabled="work_state==1">
            <el-option v-for="item in com_options" :key="item.id" :label="item.label" :value="item.label" />
          </el-select>
          <el-button type="primary" size="large" :icon="RefreshRight" @click="refresh_com(1)" :disabled="work_state==1"/>
        </div>
        <el-button size="large" type="primary" class="w-1/6" @click="r2k_set(conf.stream[0].com_2)" :disabled="work_state==1"> 连接</el-button >
      </div>
      <div class="mx-2 my-1 flex">
        <el-checkbox label="通道2开启" class="w-1/6" v-model="conf.stream[1].enable" size="large" :disabled="work_state==1"/>
        <div class="w-1/3">
          <el-select size="large" v-model="conf.stream[1].com_1" value-key="id" placeholder="选择产线设备"  style="width: 240px" :disabled="work_state==1">
            <el-option v-for="item in com_options" :key="item.id" :label="item.label" :value="item.label" />
          </el-select>
          <el-button type="primary" size="large" :icon="RefreshRight" @click="refresh_com(2)" :disabled="work_state==1"/>
        </div>
        <div class="w-1/3">
          <el-select class="ml-2" size="large" v-model="conf.stream[1].com_2" value-key="id" placeholder="选择读头设备" style="width: 240px" :disabled="work_state==1">
            <el-option v-for="item in com_options" :key="item.id" :label="item.label" :value="item.label" />
          </el-select>
          <el-button type="primary" size="large" :icon="RefreshRight" @click="refresh_com(3)" :disabled="work_state==1"/>
        </div>

        <el-button size="large" type="primary" class="w-1/6 " @click="r2k_set(conf.stream[1].com_2)" :disabled="work_state==1"> 连接</el-button >
      </div>

    </div>

    <div class="px-5 mx-2 pt-2 pb-2 mb-4 border rounded-lg bg-slate-300">    
      <div class="mx-2 my-2">
        <el-button class="w-1/8 mr-10" type="primary" size="large" :loading="conf_state==1" :disabled="conf_state==2 || work_state==1" @click="get_conf"> 获取配置</el-button>
        <el-button class="w-1/8 mr-10" type="primary" size="large" :loading="conf_state==2" :disabled="conf_state==1" @click="set_conf"> 保存配置</el-button>
        <el-button class="w-1/8 mr-10" type="primary" size="large" :disabled="work_state==0" @click="apply_conf"> 应用配置</el-button>
        <el-button class="w-1/5" :type="work_state === 0 ? 'primary' : 'danger'"  size="large" @click="start" >{{ work_state === 0 ? '开始' : '停止' }}</el-button>
      </div>
    </div>


  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { invoke } from '@tauri-apps/api/tauri'
import { RefreshRight} from '@element-plus/icons-vue';
import { emit } from '@tauri-apps/api/event'
import { ElMessage } from 'element-plus'

const work_state = ref<number>(0)
const conf_state = ref<number>(0)

interface Msg {
  msg_text:string,
  msg_type:string,
}

interface Stream {
  enable:boolean,
  com_1:string,
  com_2:string
}

interface Filter {
  epc: String,
  tid: String,
  rssi: number,
  enable: boolean,
}

interface StartConf {
    mode: string;
    save: {enable:boolean,detail:boolean,path:string,volu:string};
    stream: [Stream,Stream];
    filter: [Filter, Filter];
}

type PortInfoTuple = [string, string];
type ResultArrayType = PortInfoTuple[];

type Option = {
  id: number
  label: string
  desc: string
}
const com_options = ref<Option[]>([])

const conf = ref<StartConf>({
  mode:"trans",
  save:{enable:false,detail:false,path:"",volu:""},
  stream:[{enable:false,com_1:"",com_2:""},{enable:false,com_1:"",com_2:""}],
  filter:[{epc:"",tid:"",rssi:0,enable:false},{epc:"",tid:"",rssi:0,enable:false}]
})

async function get_conf () {
  conf_state.value = 1;
  await invoke("get_gw_conf_cmd")
  .then((res ) =>{
    conf.value = res as StartConf;
  })
  .catch((e) => console.error(e))
  conf_state.value = 0;
}

async function set_conf () {
  conf_state.value = 2;
  await invoke("set_gw_conf_cmd",{conf:conf.value})
  .then((res ) =>{
    const mssage = res as string;
    ElMessage({ message: mssage, type: 'success', offset:50});

  })
  .catch((e) => console.error(e))
  conf_state.value = 0;
}

function apply_conf(){
  emit('muhlbauer', { head: 'work_set', content: JSON.stringify(conf.value)})
}

async function list_port () {
  let result: ResultArrayType = await invoke("list_com_cmd");
  console.log(result)
  com_options.value = [];
  let currentId = 1;
  result.forEach(element => {
    com_options.value.push({id:currentId++,label:element[0],desc:element[1]})
  });
}

function refresh_com(ch_com:number){
  list_port();
  switch (ch_com){
    case 0:
      conf.value.stream[0].com_1 = ""
      break;
    case 1:
      conf.value.stream[0].com_2 = ""
      break;
    case 2:
      conf.value.stream[1].com_1 = ""
      break;
    case 3:
      conf.value.stream[1].com_2 = ""
      break;
  }
}

async function r2k_set(com:string){
  work_state.value = 1;
  console.log(com)
  // 功能不完善暂且不使用
  await invoke("r2k_set_cmd",{port: com})
  .then((res ) =>{
    console.log(res);
  })
  .catch((e) => console.error(e))
  work_state.value = 0;
}

async function r2k_start(){
  work_state.value = 1;
  let result: Msg | null = await invoke("r2k_start_cmd",{conf:conf.value});
  if(result){
    (ElMessage as any)({ message: result.msg_text, type: result.msg_type, offset:50})
    if (result.msg_type == "error") {
      emit('muhlbauer', { head: 'work_stop', content: ''})
    }
  }
  work_state.value = 0;
}

async function start(){
  switch (work_state.value){
    case 0:
      if (conf.value.stream[0].enable && (!conf.value.stream[0].com_1 || !conf.value.stream[0].com_2)){
        ElMessage({ message: '设备连接设置：请选择端口', type: 'warning', offset:50})
        break;
      }
      if (conf.value.stream[1].enable && (!conf.value.stream[1].com_1 || !conf.value.stream[1].com_2)){
        ElMessage({ message: '设备连接设置：请选择端口', type: 'warning', offset:50})
        break;
      }
      await r2k_start()
      break;
    case 1:
      // 也许该用invoke
      emit('muhlbauer', { head: 'work_stop', content: ''})
      work_state.value = 0;
      break;
    default:
      ElMessage({ message: 'start：状态错误', type: 'error', offset:50})
  }
}


onMounted(async () => {
  get_conf();
  list_port();
});

</script>



<style>

</style>